<template>
  <div class="flex-1 flex flex-col h-screen bg-gray-100">
    <!-- 顶部占位符 -->
    <div class="bg-white p-4 border-b flex justify-between items-center">
      <h1 class="text-xl font-bold">AI 视频生成</h1>
      <el-button
        type="primary"
        :loading="isLoading"
        @click="handleGenerate"
        class="!rounded-button"
      >
        <el-icon class="mr-1"><VideoPlay /></el-icon>
        生成视频
      </el-button>
    </div>

    <!-- 平台选择标签页 -->
    <div class="bg-white border-b px-6 py-2">
      <el-tabs v-model="currentPlatform" @tab-change="handlePlatformChange">
        <el-tab-pane label="Pixverse" name="pixverse">
          <template #label>
            <div class="flex items-center">
              <!-- 替换为 Pixverse 图标 -->
              <span class="w-5 h-5 mr-2">🌌</span> Pixverse
            </div>
          </template>
        </el-tab-pane>
        <el-tab-pane label="快手可灵" name="kling">
          <template #label>
            <div class="flex items-center">
              <!-- 替换为快手可灵图标 -->
              <span class="w-5 h-5 mr-2">✨</span> 快手可灵
            </div>
          </template>
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 主体内容区 -->
    <div class="flex-1 overflow-y-auto p-6 flex gap-6">
      <!-- 左侧参数设置 -->
      <div class="w-2/5 bg-white rounded-lg shadow-sm p-6 self-start sticky top-6">
        <h2 class="text-lg font-medium mb-4">参数设置</h2>

        <!-- Pixverse 参数 -->
        <div v-if="currentPlatform === 'pixverse'">
          <el-form label-position="top">
            <el-form-item label="模型">
              <el-select
                v-model="pixverseParams.model"
                placeholder="选择模型"
                class="w-full"
                @change="handleModelChange"
              >
                <el-option
                  v-for="item in pixverseModels"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="宽高比">
              <el-input v-model="pixverseParams.ratio" placeholder="例如: 16:9, 1:1, 9:16" />
            </el-form-item>

            <!-- 特效选择 (仅 v3) -->
            <el-form-item label="特效 (仅 v3 模型支持)" v-if="showPixverseTemplates">
              <div class="text-sm text-gray-500 mb-2">选择一个特效模板:</div>
              <div
                class="grid grid-cols-2 sm:grid-cols-3 gap-3 max-h-96 overflow-y-auto p-1 border rounded-md"
              >
                <el-card
                  v-for="template in pixverseTemplates"
                  :key="template.id"
                  shadow="hover"
                  :body-style="{ padding: '0px' }"
                  class="cursor-pointer relative"
                  :class="{ 'ring-2 ring-blue-500': pixverseParams.template_id === template.id }"
                  @click="selectTemplate(template.id)"
                >
                  <el-image
                    :src="
                      template.imageUrl ||
                      'https://via.placeholder.com/150/EEEEEE/AAAAAA?text=No+Preview'
                    "
                    fit="cover"
                    class="w-full h-24"
                    lazy
                  >
                    <template #placeholder>
                      <div class="image-slot">加载中<span class="dot">...</span></div>
                    </template>
                    <template #error>
                      <div
                        class="image-slot flex items-center justify-center h-full bg-gray-100 text-gray-500"
                      >
                        <el-icon><Picture /></el-icon>
                      </div>
                    </template>
                  </el-image>
                  <div class="p-2 text-center">
                    <span class="text-xs font-medium truncate block">{{ template.name }}</span>
                    <el-tooltip
                      v-if="template.description"
                      :content="template.description"
                      placement="top"
                    >
                      <el-icon class="text-gray-400 ml-1 text-xs"><InfoFilled /></el-icon>
                    </el-tooltip>
                  </div>
                  <div
                    v-if="pixverseParams.template_id === template.id"
                    class="absolute top-1 right-1 bg-blue-500 text-white rounded-full p-0.5"
                  >
                    <el-icon size="12"><Select /></el-icon>
                  </div>
                </el-card>
              </div>
              <div v-if="pixverseParams.template_id" class="mt-2 text-xs text-blue-600">
                已选择特效:
                {{ pixverseTemplates.find((t) => t.id === pixverseParams.template_id)?.name }} (ID:
                {{ pixverseParams.template_id }})
                <el-button
                  type="text"
                  size="small"
                  @click="pixverseParams.template_id = null"
                  class="ml-1"
                  >清除</el-button
                >
              </div>
            </el-form-item>
          </el-form>
        </div>

        <!-- 快手可灵参数 (占位) -->
        <div v-if="currentPlatform === 'kling'">
          <p class="text-gray-500">快手可灵的参数设置区域</p>
          <!-- 在这里添加快手可灵的表单项 -->
        </div>

        <!-- 通用提示词 -->
        <el-form-item label="提示词" class="mt-4">
          <el-input
            v-model="prompt"
            type="textarea"
            :rows="6"
            placeholder="输入详细的视频内容描述..."
            maxlength="500"
            show-word-limit
            :resize="'vertical'"
          />
          <div class="text-xs text-gray-500 mt-1">
            提示：输入清晰、具体的描述可以提高生成效果，建议保持在200-300字左右
          </div>
        </el-form-item>

        <el-button
          type="primary"
          :loading="isLoading"
          @click="handleGenerate"
          class="w-full !rounded-button mt-4"
        >
          <el-icon class="mr-1"><VideoPlay /></el-icon>
          生成视频
        </el-button>
      </div>

      <!-- 右侧结果展示 -->
      <div class="w-3/5">
        <h2 class="text-lg font-medium mb-4">生成结果</h2>
        <div
          v-if="generationResults.length === 0 && !isLoading"
          class="text-center text-gray-500 mt-10"
        >
          暂无生成记录，快来创建你的第一个 AI 视频吧！
        </div>
        <div
          v-if="isLoading && generationResults.length === 0"
          class="text-center text-gray-500 mt-10"
        >
          <el-icon class="is-loading mr-1" size="16"><Loading /></el-icon>
          正在处理第一个任务...
        </div>

        <div class="space-y-4">
          <el-card
            v-for="result in generationResults"
            :key="result.id"
            shadow="never"
            class="!rounded-lg"
          >
            <div class="flex gap-4">
              <!-- 视频/占位符区域 -->
              <div class="w-1/3">
                <div
                  v-if="result.status === 2 && result.videoUrl"
                  class="aspect-video bg-black rounded overflow-hidden"
                >
                  <video
                    controls
                    :src="result.videoUrl"
                    :poster="result.poster"
                    class="w-full h-full"
                  ></video>
                </div>
                <div
                  v-else
                  class="aspect-video bg-gray-200 rounded flex items-center justify-center text-gray-500"
                >
                  <div v-if="result.status === 1" class="text-center">
                    <el-icon class="is-loading text-xl mb-1"><Loading /></el-icon>
                    <p class="text-xs">生成中...</p>
                  </div>
                  <div v-else-if="result.status === 3" class="text-center text-red-500">
                    <el-icon class="text-xl mb-1"><CircleCloseFilled /></el-icon>
                    <p class="text-xs">生成失败</p>
                  </div>
                  <div v-else class="text-center">
                    <el-icon class="text-xl mb-1"><VideoCamera /></el-icon>
                    <p class="text-xs">等待生成</p>
                  </div>
                </div>
              </div>
              <!-- 任务信息区域 -->
              <div class="w-2/3 text-sm">
                <el-tooltip
                  :content="result.prompt"
                  placement="top"
                  :show-after="500"
                  :enterable="false"
                >
                  <p class="font-medium mb-1 line-clamp-2 text-ellipsis">
                    {{ result.prompt || '无提示词' }}
                  </p>
                </el-tooltip>
                <div class="text-xs text-gray-500 space-y-0.5 mb-2">
                  <p>平台: {{ result.platform }}</p>
                  <p v-if="result.platform === 'pixverse'">
                    模型: {{ result.params.model }} | 宽高比: {{ result.params.ratio }}
                  </p>
                  <p v-if="result.params.template_name">特效: {{ result.params.template_name }}</p>
                  <p>时间: {{ formatDate(result.createdAt) }}</p>
                </div>
                <div class="flex flex-wrap gap-2 items-center mt-2">
                  <el-tag
                    :type="statusTypeMap[result.status]"
                    size="small"
                    effect="light"
                    class="!rounded-button"
                  >
                    {{ statusMap[result.status] }}
                  </el-tag>
                  <!-- 添加下载和重试按钮 -->
                  <a
                    v-if="result.status === 2 && result.videoUrl"
                    :href="result.videoUrl"
                    download
                    target="_blank"
                    class="el-button el-button--primary el-button--small is-link"
                    >下载</a
                  >
                  <el-button
                    v-if="result.status === 3"
                    type="danger"
                    link
                    size="small"
                    @click="retryTask(result.id, result.prompt)"
                    >重试</el-button
                  >
                </div>
              </div>
            </div>
          </el-card>

          <!-- 分页控件 -->
          <div class="flex justify-center mt-6" v-if="pagination.totalPage > 0">
            <el-pagination
              v-model:currentPage="pagination.currentPage"
              v-model:page-size="pagination.pageSize"
              :page-sizes="[5, 10, 20, 50]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="pagination.total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              background
            />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { ref, computed, onMounted, onBeforeUnmount } from 'vue'
import {
  ElMessage,
  ElTabs,
  ElTabPane,
  ElForm,
  ElFormItem,
  ElSelect,
  ElOption,
  ElInput,
  ElButton,
  ElCard,
  ElImage,
  ElIcon,
  ElTooltip,
  ElTag,
  ElLoading,
  ElPagination,
} from 'element-plus'
import {
  VideoPlay,
  Back,
  Refresh,
  Picture,
  InfoFilled,
  Select,
  Loading,
  CircleCloseFilled,
  VideoCamera,
} from '@element-plus/icons-vue'
import type { TabsPaneContext } from 'element-plus'
import {
  submitPixverseVideoTask,
  queryPixverseVideoTask,
  getVideoTaskPage,
  VideoTaskItem,
  PageParams,
} from '@/api/video'

// 定义 Pixverse 特效数据结构
interface PixverseTemplate {
  id: number
  name: string
  description?: string
  imageUrl?: string
  videoUrl?: string
}

// 定义生成结果数据结构
interface GenerationResult {
  id: number
  platform: string
  prompt: string
  params: any
  status: number // 0: NOT_START, 1: IN_PROGRESS, 2: FAILURE, 3: SUCCESS
  videoUrl?: string // 成功后会有视频地址
  poster?: string // 添加封面地址
  createdAt: number | Date
}

export default {
  name: 'AiVideo',
  components: {
    // 注册图标组件，以便在 template 中使用
    VideoPlay,
    Picture,
    InfoFilled,
    Select,
    Loading,
    CircleCloseFilled,
    VideoCamera,
  },
  setup() {
    const currentPlatform = ref('pixverse')
    const prompt = ref('')
    const isLoading = ref(false)
    const isQueryTask = ref(false)
    const generationResults = ref<GenerationResult[]>([])
    const currentVideoId = ref<number | null>(null) // 用于存储当前生成的视频ID
    const queryTimer = ref<number | null>(null) // 用于存储轮询定时器ID

    // 分页相关状态
    const pagination = ref({
      currentPage: 1,
      pageSize: 10,
      total: 0,
      totalPage: 0,
      order: 'DESC' as 'ASC' | 'DESC',
      field: 'create_time',
    })

    const pixverseParams = ref({
      model: 'v4',
      ratio: '16:9',
      template_id: null as number | null,
    })

    const klingParams = ref({
      // 快手可灵的参数（占位）
    })

    const pixverseModels = [
      { value: 'v2', label: 'v2' },
      { value: 'v3', label: 'v3 (支持特效)' },
      { value: 'v3.5', label: 'v3.5' },
      { value: 'v4', label: 'v4 (最新, 540p, 极速)' },
    ]

    // 解析并存储 Pixverse 特效数据
    const pixverseTemplates: PixverseTemplate[] = [
      { id: 316139945292864, name: '鱿鱼游戏' },
      { id: 317013620689664, name: '英姬的凝视' },
      { id: 315446232403008, name: '娃娃脸特效' },
      { id: 315446315336768, name: '爱的亲亲' },
      { id: 302325299721280, name: '活灵活现' },
      { id: 308621408717184, name: '肌肉男' },
      { id: 308552687706496, name: '长发' },
      { id: 307489434436288, name: '小丑女哈莉·奎茵变身' },
      { id: 307489548427968, name: '疯狂猫女变身' },
      { id: 309283958194560, name: '神奇女侠变身' },
      { id: 310371322329472, name: '羊毛卷' },
      { id: 311521768592256, name: '圣诞礼物盲盒' },
      { id: 311521879229312, name: '圣诞老人藏在哪？' },
      { id: 312314911869312, name: '圣诞战袍' },
      { id: 313359209531840, name: '黑悟空引擎' },
      { id: 313359138372032, name: '成为美少女战士' },
      {
        id: 304826314164992,
        name: '召唤绿巨人',
        description: '变身成绿巨人并捶爆一切',
        imageUrl:
          'https://media.pixverse.ai/asset%2Ftemplate%2Flvjvren.png?x-oss-process=style/cover-webp',
        videoUrl: 'https://media.pixverse.ai/asset%2Ftemplate%2Flvjvren.mp4',
      },
      {
        id: 304826126435072,
        name: '小丑重生',
        description: '变身成小丑，诡异地微笑',
        imageUrl:
          'https://media.pixverse.ai/asset%2Ftemplate%2Fjoker.png?x-oss-process=style/cover-webp',
        videoUrl: 'https://media.pixverse.ai/asset%2Ftemplate%2Fjoker.mp4',
      },
      {
        id: 304826054394624,
        name: '钢铁侠变身',
        description: '激活钢铁模式',
        imageUrl:
          'https://media.pixverse.ai/asset%2Ftemplate%2Fironman.png?x-oss-process=style/cover-webp',
        videoUrl: 'https://media.pixverse.ai/asset%2Ftemplate%2Fironman.mp4',
      },
      {
        id: 304826374632192,
        name: '蝙蝠侠归来',
        description: '变身成蝙蝠侠并守护黑夜',
        imageUrl:
          'https://media.pixverse.ai/asset%2Ftemplate%2Fbatman.png?x-oss-process=style/cover-webp',
        videoUrl: 'https://media.pixverse.ai/asset%2Ftemplate%2Fbatman.mp4',
      },
      {
        id: 303788802773760,
        name: 'Wicked Shots',
        imageUrl:
          'https://media.pixverse.ai/asset%2Ftemplate%2Fwicked_shots_241028.png?x-oss-process=style/cover-webp',
        videoUrl: 'https://media.pixverse.ai/asset%2Ftemplate%2Fwicked_shots_241028.mp4',
      },
      {
        id: 303624537709312,
        name: '毒液变身We Are Venom!',
        imageUrl:
          'https://media.pixverse.ai/asset%2Ftemplate%2Fvenom.png?x-oss-process=style/cover-webp',
        videoUrl: 'https://media.pixverse.ai/asset%2Ftemplate%2Fvenom.mp4',
      },
      {
        id: 304358279051648,
        name: '毒液！(彩色盲盒版)',
        imageUrl:
          'https://media.pixverse.ai/asset%2Ftemplate%2Fvenom33.png?x-oss-process=style/cover-webp',
        videoUrl: 'https://media.pixverse.ai/asset%2Ftemplate%2Fvenom33.mp4',
      },
      {
        id: 303624424723200,
        name: 'Hug Your Love',
        imageUrl:
          'https://media.pixverse.ai/asset%2Ftemplate%2Fhug2.png?x-oss-process=style/cover-webp',
        videoUrl: 'https://media.pixverse.ai/asset%2Ftemplate%2Fhug2.mp4',
      },
      {
        id: 302325299651648,
        name: 'Zombie Mode',
        imageUrl:
          'https://media.pixverse.ai/asset%2Ftemplate%2Fassetmediazombie2.png?x-oss-process=style/cover-webp',
        videoUrl: 'https://media.pixverse.ai/asset%2Ftemplate%2Fzombie2_241031.mp4',
      },
      {
        id: 302325299692608,
        name: 'Squish It',
        imageUrl:
          'https://media.pixverse.ai/asset%2Ftemplate%2Fsquish_it_241028_1.png?x-oss-process=style/cover-webp',
        videoUrl: 'https://media.pixverse.ai/asset%2Ftemplate%2Fsquish_it_241028_1.mp4',
      },
      {
        id: 302325299672128,
        name: 'Zombie Hand',
        imageUrl:
          'https://media.pixverse.ai/asset%2Ftemplate%2Fzombie_hand_241028.png?x-oss-process=style/cover-webp',
        videoUrl: 'https://media.pixverse.ai/asset%2Ftemplate%2Fzombie_hand_241028.mp4',
      },
      // 过滤掉 "下架" 的特效
      // { id: 302325299661888, name: '下架Wizard Hat', imageUrl: '...', videoUrl: '...' },
      // { id: 302325299661888, name: '下架Out of Frame', imageUrl: '...', videoUrl: '...' },
      {
        id: 302325299711040,
        name: 'Leggy Run',
        imageUrl:
          'https://media.pixverse.ai/asset%2Ftemplate%2Fleggy_run_241028.png?x-oss-process=style/cover-webp',
        videoUrl: 'https://media.pixverse.ai/asset%2Ftemplate%2Fleggy_run_241028.mp4',
      },
      {
        id: 302325299682368,
        name: 'Monster Invades',
        imageUrl:
          'https://media.pixverse.ai/asset%2Ftemplate%2Fmonster_invasion_241028.png?x-oss-process=style/cover-webp',
        videoUrl: 'https://media.pixverse.ai/asset%2Ftemplate%2Fmonster_invasion_241028.mp4',
      },
      {
        id: 302325299702848,
        name: 'Lego Blast',
        imageUrl:
          'https://media.pixverse.ai/asset%2Ftemplate%2Flego_blast_241028.png?x-oss-process=style/cover-webp',
        videoUrl: 'https://media.pixverse.ai/asset%2Ftemplate%2Flego_blast_241028.mp4',
      },
    ]

    const statusMap: Record<number, string> = {
      0: '未开始',
      1: '生成中',
      2: '成功',
      3: '失败',
    }

    const statusTypeMap: Record<number, 'info' | 'warning' | 'danger' | 'success'> = {
      0: 'info',
      1: 'warning',
      2: 'success',
      3: 'danger',
    }

    const showPixverseTemplates = computed(() => {
      return currentPlatform.value === 'pixverse' && pixverseParams.value.model === 'v3'
    })

    // 加载任务列表
    const loadTaskList = async () => {
      try {
        const pageParams: PageParams = {
          page: pagination.value.currentPage,
          limit: pagination.value.pageSize,
          order: pagination.value.order,
          field: pagination.value.field,
        }

        const response = await getVideoTaskPage({ page: pageParams })
        if (response) {
          // 更新分页信息
          pagination.value.total = response.totalCount
          pagination.value.totalPage = response.totalPage

          // 转换API返回的数据格式为页面使用的格式
          if (response.data) {
            const results: GenerationResult[] = response.data.map((item: VideoTaskItem) => ({
              id: item.id,
              platform: item.platformId === 1 ? 'pixverse' : 'other', // 根据platformId判断平台
              prompt: item.prompt,
              params: {
                model: item.model,
                ratio: item.radio,
                template_id: item.templateId,
              },
              status: item.status,
              videoUrl: item.videoUrl,
              poster: item.poster,
              createdAt: item.createTime,
            }))
            generationResults.value = results
          }
        }
      } catch (error) {
        console.error('加载任务列表失败:', error)
        ElMessage.error('加载历史任务失败')
      }
    }

    // 当模型改变时，如果不是v3，则清空特效选择
    const handleModelChange = (modelValue: string) => {
      if (modelValue !== 'v3') {
        pixverseParams.value.template_id = null
      }
    }

    // 处理平台切换
    const handlePlatformChange = (pane: TabsPaneContext) => {
      const name = pane.paneName as string
      console.log('切换到平台:', name)
    }

    // 查询单个任务状态
    const queryTaskStatus = async (videoId: number) => {
      if (!videoId || isQueryTask.value) return

      isQueryTask.value = true
      try {
        const result = await queryPixverseVideoTask(videoId)
        if (result) {
          // 更新对应的任务状态
          const index = generationResults.value.findIndex((item) => item.id === videoId)
          if (index !== -1) {
            const taskResult = generationResults.value[index]
            taskResult.status = result.status
            taskResult.videoUrl = result.videoUrl
            taskResult.poster = result.poster

            // 如果任务已完成（成功或失败），清除轮询定时器
            if (result.status === 2 || result.status === 3) {
              if (queryTimer.value) {
                clearInterval(queryTimer.value)
                queryTimer.value = null
              }

              if (result.status === 2) {
                ElMessage.success('视频生成成功！')
              } else if (result.status === 3) {
                ElMessage.error(`视频生成失败：${result.statusDesc || '未知错误'}`)
              }

              // 任务完成后，重新加载任务列表以获取最新状态
              loadTaskList()
            }
          }
        }
      } catch (error) {
        console.error('查询任务状态失败:', error)
      } finally {
        isQueryTask.value = false
      }
    }

    // 开始轮询任务状态
    const startPollingTaskStatus = (videoId: number) => {
      // 先清除可能存在的定时器
      if (queryTimer.value) {
        clearInterval(queryTimer.value)
      }

      // 立即查询一次
      queryTaskStatus(videoId)

      // 设置定时器，每5秒查询一次
      queryTimer.value = setInterval(() => {
        queryTaskStatus(videoId)
      }, 5000) as unknown as number
    }

    // 处理生成按钮点击
    const handleGenerate = async () => {
      if (!prompt.value.trim()) {
        ElMessage.warning('请输入提示词')
        return
      }

      // 检查提示词长度
      if (prompt.value.length > 500) {
        ElMessage.warning('提示词过长，请控制在500字以内')
        return
      }

      // 如果提示词太短，给出友好提示
      if (prompt.value.length < 10) {
        ElMessage.warning('提示词太短，建议提供更详细的描述以获得更好的效果')
        return
      }

      isLoading.value = true
      try {
        if (currentPlatform.value === 'pixverse') {
          // 准备请求参数
          const params = {
            platform: 1, // Pixverse平台固定为1
            model: pixverseParams.value.model,
            prompt: prompt.value,
            radio: pixverseParams.value.ratio,
            // 如果有特效ID且使用v3模型，则添加模板ID
            ...(pixverseParams.value.template_id && pixverseParams.value.model === 'v3'
              ? { templateId: pixverseParams.value.template_id.toString() }
              : {}),
          }

          // 提交任务
          const response = await submitPixverseVideoTask(params)
          if (response && response.videoId) {
            // 获取生成的视频ID
            currentVideoId.value = response.videoId

            // 创建初始任务记录
            const newResult: GenerationResult = {
              id: response.videoId,
              platform: currentPlatform.value,
              prompt: prompt.value,
              params: {
                model: params.model,
                ratio: params.radio,
                template_id: pixverseParams.value.template_id,
                template_name: pixverseParams.value.template_id
                  ? pixverseTemplates.find((t) => t.id === pixverseParams.value.template_id)?.name
                  : undefined,
              },
              status: 1, // IN_PROGRESS
              createdAt: new Date(),
            }

            // 添加到结果列表顶部
            generationResults.value.unshift(newResult)

            // 开始轮询任务状态
            startPollingTaskStatus(response.videoId)

            ElMessage.success('视频任务提交成功，正在处理中...')
          }
        } else if (currentPlatform.value === 'kling') {
          // 暂未实现 快手可灵 的接口
          ElMessage.warning('快手可灵接口暂未实现')
        }
      } catch (error) {
        console.error('提交视频任务失败:', error)
        ElMessage.error('视频任务提交失败')
      } finally {
        isLoading.value = false
      }
    }

    // 选择特效卡片
    const selectTemplate = (templateId: number) => {
      if (pixverseParams.value.template_id === templateId) {
        pixverseParams.value.template_id = null // 再次点击取消选择
      } else {
        pixverseParams.value.template_id = templateId
      }
    }

    // 重试失败的任务
    const retryTask = async (id: number, prompt: string) => {
      if (currentPlatform.value === 'pixverse') {
        isLoading.value = true
        try {
          // 重新提交相同的任务
          const params = {
            platform: 1,
            model: pixverseParams.value.model,
            prompt: prompt,
            radio: pixverseParams.value.ratio,
          }

          const response = await submitPixverseVideoTask(params)
          if (response && response.videoId) {
            // 从列表中移除旧任务
            const index = generationResults.value.findIndex((item) => item.id === id)
            if (index !== -1) {
              generationResults.value.splice(index, 1)
            }

            // 添加新任务到列表
            const newResult: GenerationResult = {
              id: response.videoId,
              platform: 'pixverse',
              prompt: prompt,
              params: {
                model: params.model,
                ratio: params.radio,
              },
              status: 1,
              createdAt: new Date(),
            }

            generationResults.value.unshift(newResult)

            // 开始轮询新任务状态
            startPollingTaskStatus(response.videoId)

            ElMessage.success('重新提交任务成功！')
          }
        } catch (error) {
          console.error('重试任务失败:', error)
          ElMessage.error('重试任务失败')
        } finally {
          isLoading.value = false
        }
      }
    }

    // 格式化日期
    const formatDate = (timestamp: number | Date): string => {
      const date = timestamp instanceof Date ? timestamp : new Date(timestamp)
      return date.toLocaleString()
    }

    // 处理页码变化
    const handleCurrentChange = (page: number) => {
      pagination.value.currentPage = page
      loadTaskList()
    }

    // 处理每页条数变化
    const handleSizeChange = (size: number) => {
      pagination.value.pageSize = size
      pagination.value.currentPage = 1 // 重置到第一页
      loadTaskList()
    }

    // 初始加载历史任务和组件销毁时清理定时器
    onMounted(() => {
      loadTaskList()
    })

    onBeforeUnmount(() => {
      if (queryTimer.value) {
        clearInterval(queryTimer.value)
      }
    })

    return {
      currentPlatform,
      prompt,
      pixverseParams,
      klingParams,
      pixverseModels,
      pixverseTemplates,
      showPixverseTemplates,
      isLoading,
      generationResults,
      statusMap,
      statusTypeMap,
      handlePlatformChange,
      handleModelChange,
      handleGenerate,
      selectTemplate,
      retryTask,
      formatDate,
      pagination,
      handleCurrentChange,
      handleSizeChange,
    }
  },
}
</script>

<style scoped>
/* 添加可能需要的特定样式 */
.aspect-video {
  aspect-ratio: 16 / 9;
}
/* Element Plus Image Slot Styles */
.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: var(--el-fill-color-light);
  color: var(--el-text-color-secondary);
  font-size: 14px;
}
.image-slot .dot {
  animation: dot 1.4s infinite ease-in-out both;
  display: inline-block;
  margin-left: 2px;
}
.image-slot .dot:nth-child(1) {
  animation-delay: -0.32s;
}
.image-slot .dot:nth-child(2) {
  animation-delay: -0.16s;
}
@keyframes dot {
  0%,
  80%,
  100% {
    content: '.';
  }
  40% {
    content: '..';
  }
  60% {
    content: '...';
  }
}

/* 自定义圆角按钮 */
.el-button.is-round {
  border-radius: 9999px;
}
.el-tag.is-round {
  border-radius: 9999px;
}
/* Or force rounded style */
.rounded-button {
  border-radius: 9999px !important;
}

/* 强制sticky元素在父滚动容器内 */
.sticky {
  position: -webkit-sticky; /* Safari */
  position: sticky;
}

/* 确保模板网格滚动 */
.max-h-96 {
  max-height: 24rem; /* 384px */
}

/* 文本截断样式 */
.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.text-ellipsis {
  text-overflow: ellipsis;
}
</style>
